# -*- coding: utf-8 -*-
__author__ = 'zaxlct'
__date__ = '2017/9/30 下午3:48'



## 获取访客IP
def check_user_ip(request):
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        client_ip = request.META['HTTP_X_FORWARDED_FOR']
        client_ip = client_ip.split(",")[0]
        #print("HTTP_X_FORWARDED_FOR")
        return client_ip
    elif 'REMOTE_ADDR' in request.META:
        client_ip = request.META['REMOTE_ADDR']
        #print("REMOTE_ADDR")  OK
        return client_ip
    else:
        return ''


## 获取访客IP 计入字典 返回字符串
def get_user_ip(request):
    if 'REMOTE_ADDR' in request.META:
        client_ip = request.META['REMOTE_ADDR']
    else:
        client_ip = ''
    if not client_ip:
        return False, ''

    ipaddress = request.user.ipaddress if request.user.is_authenticated() else ''
    if ipaddress:
        # 更新新版IP地址
        if "{" in ipaddress:
            ipaddress = eval(ipaddress)
            if isinstance(ipaddress,dict):
                if str(client_ip) in ipaddress.keys():
                    ipaddress[str(client_ip)] += 1
                else:
                    ipaddress.setdefault(str(client_ip),1)
                return True, str(ipaddress)
            else:
                return False, ''

        # 更新旧版IP地址 已存多个IP地址
        elif ";" in ipaddress and "{" not in ipaddress:
            iplist = ipaddress.split(";")
            while '' in iplist:
                iplist.remove('')
            iplist = list(set(iplist))
            new_ipaddress = dict()
            [new_ipaddress.setdefault(str(ip),1) for ip in iplist]
            if str(client_ip) in new_ipaddress.keys():
                new_ipaddress[str(client_ip)] += 1
            else:
                new_ipaddress.setdefault(str(client_ip), 1)
            return True, str(new_ipaddress)

        # 更新旧版IP地址 只有一个IP地址
        else:
            new_ipaddress = dict()
            if (str(client_ip)==str(ipaddress)):
                new_ipaddress.setdefault(str(ipaddress), 2)
            else:
                new_ipaddress.setdefault(str(ipaddress), 1)
                new_ipaddress.setdefault(str(client_ip), 1)
            return True, str(new_ipaddress)

    else:
        # 首次存储IP地址
        new_ipaddress = dict()
        new_ipaddress.setdefault(str(client_ip),1)
        return True, str(new_ipaddress)






## 分析访客入口页面
## 是从哪个页面跳转进入的
def check_user_form_page(request):
    pass